package com.foton.logistic.fragment;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.foton.logistic.R;
import com.foton.logistic.activity.CityActivity;
import com.foton.logistic.activity.RemindActivity;
import com.foton.logistic.base.BaseApplication;
import com.foton.logistic.base.BaseFragment;
import com.foton.logistic.listener.IOnResultListener;
import com.foton.logistic.model.WeatherResult;
import com.foton.logistic.task.DispatchTask;
import com.foton.logistic.task.ShowDialogTask;
import com.foton.logistic.task.TaskConstant;
import com.foton.logistic.util.BaseConstant;
import com.foton.logistic.util.BroadcastUtil;
import com.foton.logistic.util.OptionUtil;
import com.foton.logistic.util.SharedUtil;
import com.foton.logistic.util.net.HttpUtil;
import com.foton.logistic.util.tool.DensityUtil;
import com.foton.logistic.util.tool.JacksonUtil;
import com.foton.logistic.util.tool.LogUtil;
import com.foton.logistic.util.tool.StringUtil;
import com.foton.logistic.view.CloudImageView;
import com.foton.logistic.view.Square;
import com.foton.logistic.view.chooseimages.ChooseImagesSampleActivity;

import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import butterknife.Optional;


public class HomeFragment extends BaseFragment {
    public View rootView;
    @InjectView(R.id.base_ui_title_location)
    TextView homeCity;
    @InjectView(R.id.ft_fragment_home_weather_temperature)
    TextView homeWeatherTemperature;
    @InjectView(R.id.ft_fragment_home_weather_icon)
    ImageView homeWeatherImg;
    @InjectView(R.id.ft_fragment_home_weather_bg_layout)
    LinearLayout weatherBgLayout;
    @InjectView(R.id.ft_fragment_home_weather_layout)
    FrameLayout weatherLayout;
    @InjectView(R.id.ft_fragment_home_weather_condition)
    TextView homeWeatherCondition;
    @InjectView(R.id.ft_fragment_home_weather_week)
    TextView homeWeatherWeek;
    @InjectView(R.id.ft_fragment_home_weather_service)
    TextView homeWeatherService;
    @InjectView(R.id.ft_fragment_home_order_layout)
    Square orderLayout;
    @InjectView(R.id.ft_fragment_home_logistic_layout)
    Square logisticLayout;
    @InjectView(R.id.ft_fragment_home_service_layout)
    Square serviceLayout;
    @InjectView(R.id.ft_fragment_home_online_consulting_layout)
    Square consultingLayout;
    CloudImageView cloudImageView;
    private ReceiveBroadcast receiveBroadcast;
    int screenWidth, itemHeight;
    float weatherRate = 0.278f;

    public HomeFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setTaskTag(getClass().getSimpleName());
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.ft_fragment_home, null);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            rootView.setLayoutParams(params);
            ButterKnife.inject(this, rootView);
            init();
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            ButterKnife.inject(this, rootView);
            if (cloudImageView != null) {
                cloudImageView.resume();
            }
            homeCity.setText(SharedUtil.getChooseCity(getContext()));

            getWeather();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (cloudImageView != null) {
            cloudImageView.pause();
        }
    }

    @Override
    public void init() {
        setTitleTextVisibility(View.VISIBLE);
        setTitleTixingVisibility(View.VISIBLE);
        registerBroad();
        BaseApplication.self().reInit();
        BaseApplication.self().location(BaseApplication.LOCTIME);
//        if (BaseApplication.self().mLocClient.isStarted()){
//            BaseApplication.self().stopLocation();
//        }
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                BaseApplication.self().startLocation(BaseApplication.LOCTIME);
//            }
//        },5000);
       /* if (BaseApplication.off){
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            //builder.setIcon(R.drawable.ic_launcher);
            builder.setTitle("设备断开");
            builder.show();
        }*/
       /* if (SharedUtil.getLogin(getActivity())) {
            Intent intent=new Intent(getContext(), CompulSuppleActivity.class);
            startActivity(intent);
           *//* new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    DialogUtil dialogUtil = new DialogUtil(getActivity());
                    dialogUtil.setOptionCount(1);
                    dialogUtil.setTitle("司机宝APP隐私政策");
                    dialogUtil.showTipDialog(weatherLayout,getString(R.string.privacy));
                    dialogUtil.setiOnDialogListener(new IOnDialogListener() {
                        @Override
                        public void onConfirm() {
                            SharedUtil.saveLogin(getActivity(),false);

                        }

                        @Override
                        public void onCancel() {

                        }

                        @Override
                        public void onOther() {

                        }
                    });

                }
            }, 500);*//*

        }*/
        homeCity.setVisibility(View.VISIBLE);
        screenWidth = OptionUtil.getScreenWidth(getActivity());
        itemHeight = (screenWidth - DensityUtil.dip2px(getActivity(), 30)) / 2;
        orderLayout.getLayoutParams().height = itemHeight;
        logisticLayout.getLayoutParams().height = itemHeight;
        serviceLayout.getLayoutParams().height = itemHeight;
        consultingLayout.getLayoutParams().height = itemHeight;
        homeWeatherImg.setVisibility(View.INVISIBLE);
        weatherLayout.getLayoutParams().height = (int) (screenWidth * weatherRate);
        if (StringUtil.isEmpty(SharedUtil.getChooseCity(getContext()))) {
            homeCity.setText(getString(R.string.location1));
        } else {
            homeCity.setText("" + SharedUtil.getChooseCity(getContext()));
        }

        updateWeatherInfo();

    }

    @OnClick({R.id.base_ui_title_location, R.id.ft_fragment_home_order_layout, R.id.ft_fragment_home_service_layout, R.id.ft_fragment_home_online_consulting_layout, R.id.ft_fragment_home_logistic_layout,R.id.base_ui_title_remind_layout})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.base_ui_title_location:
                startActivity(new Intent(getActivity(), CityActivity.class));
                break;
            case R.id.ft_fragment_home_online_consulting_layout:
                OptionUtil.addToast(getActivity(), getString(R.string.tip22));
                break;
            case R.id.ft_fragment_home_order_layout:
                BroadcastUtil.sendTabOrder(getActivity(), 1);
                break;
            case R.id.ft_fragment_home_service_layout:
                OptionUtil.addToast(getActivity(), getString(R.string.tip22));
                break;
            case R.id.ft_fragment_home_logistic_layout:
                OptionUtil.addToast(getActivity(), getString(R.string.tip22));
                break;
            case R.id.base_ui_title_remind_layout:
             Intent intent=new Intent(getActivity(),RemindActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onDestroy() {
        try {
            getActivity().unregisterReceiver(receiveBroadcast);
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

    void getWeather() {
        if (StringUtil.isEmpty(SharedUtil.getChooseCity(getActivity()))) {
            return;
        }
        if (SharedUtil.getFlagResult(getActivity()).equals(OptionUtil.getWeatherFlag(getActivity()))) {
            return;
        }
        Map<String, Object> argMap = HttpUtil.getEncryMap(getActivity());
        argMap.put("location", SharedUtil.getChooseCity(getActivity()));
        argMap.put("output", "json");
        argMap.put("ak", getString(R.string.ak));
        argMap.put("mcode", getString(R.string.mcode));
        ShowDialogTask task = new ShowDialogTask(getActivity(), taskTag, titleText, getString(R.string.task2), false, BaseConstant.baiduUrl1, argMap, TaskConstant.GET);
        task.setParseClass(WeatherResult.class);
        task.setiOnResultListener(new IOnResultListener() {
            @Override
            public void onOK(DispatchTask task) {
                SharedUtil.saveWeatherResult(getActivity(), OptionUtil.getWeatherFlag(getActivity()), task.getResultsString());
                updateWeatherInfo();
            }

            @Override
            public void onError(DispatchTask task) {
                LogUtil.e("getWeather onError=" + SharedUtil.getChooseCity(getActivity()));
            }

            @Override
            public void onDone(DispatchTask task) {

            }
        });
        task.execute();
    }


    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible) {
            return;
        }
        //TODO 判断是否加载过数据

        //TODO 网络加载

    }

    @Optional
    @OnClick(R.id.buttonbbb)
    public void setChooseImagesIntent() {
        startActivity(new Intent(getActivity(), ChooseImagesSampleActivity.class));
    }

    void updateWeatherInfo() {
        try {
            WeatherResult weatherResult = JacksonUtil.getInstance().readValue(SharedUtil.getWeatherResult(getActivity()), WeatherResult.class);
            if (weatherResult != null && weatherResult.error == 0 && weatherResult.results != null && weatherResult.results.size() > 0) {
                WeatherResult.ResultsEntity.WeatherDataEntity weatherDataEntity = weatherResult.results.get(0).weather_data.get(0);
                String date = weatherDataEntity.date.substring(0, 8);
                homeWeatherTemperature.setText(weatherDataEntity.temperature);
                homeWeatherCondition.setText(weatherDataEntity.weather);
                homeWeatherWeek.setText(date + " | ");
                homeWeatherImg.setImageResource(getImageByWeather(weatherDataEntity.weather, 1));
                homeWeatherImg.setVisibility(View.VISIBLE);
                if (StringUtil.isEmpty(weatherResult.results.get(0).index.get(1).zs)) {
                    homeWeatherService.setText("");
                } else {
                    homeWeatherService.setText("" + weatherResult.results.get(0).index.get(1).title + weatherResult.results.get(0).index.get(1).zs);
                }
                cloudImageView = new CloudImageView(getActivity(), getImageByWeather(weatherDataEntity.weather, 0));
                weatherBgLayout.removeAllViews();
                weatherBgLayout.addView(cloudImageView, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
                if (weatherDataEntity.weather.contains("雨")){
                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    //builder.setIcon(R.drawable.ic_launcher);
                    builder.setTitle("天气有雨");
                    builder.show();

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    int[] weatherBgs = {R.mipmap.wea_qing,//晴
            R.mipmap.wea_yin,//阴
            R.mipmap.wea_duoyun,//多云
            R.mipmap.wea_wu, //雾
            R.mipmap.wea_wumai,//雾霾
            R.mipmap.wea_shacb,//沙尘暴
            R.mipmap.wea_bb,//冰雹
            R.mipmap.wea_leidian,//雷电-雷阵雨-闪电
            R.mipmap.wea_xue,//雪
            R.mipmap.wea_xiaoyu,//小雨
            R.mipmap.wea_dayu,//大雨-暴雨-大到暴雨
            R.mipmap.wea_zhongyu,//中雨
            R.mipmap.wea_zhongyu,//阵雨
            R.mipmap.wea_sd};//霜冻
    int[] weatherIcons = {R.mipmap.weather_icon_sunny,
            R.mipmap.weather_icon_overcast,
            R.mipmap.weather_icon_cloudy,
            R.mipmap.weather_icon_fog,
            R.mipmap.weather_icon_dist,
            R.mipmap.weather_icon_sandy,
            R.mipmap.weather_icon_hail,
            R.mipmap.weather_icon_thunder,
            R.mipmap.weather_icon_snow,
            R.mipmap.weather_icon_rain,
            R.mipmap.weather_icon_storm,
            R.mipmap.weather_icon_zhongyu,
            R.mipmap.weather_icon_shower,
            R.mipmap.weather_icon_sd};

    /**
     * 根据天气获取图片
     *
     * @param weather
     * @param type    0是获取背景图，1是获取icon
     * @return
     */
    int getImageByWeather(String weather, int type) {
        int res = 0;
        if (weather.contains("晴")) {
            if (type == 0) {
                res = weatherBgs[0];
            } else {
                res = weatherIcons[0];
            }
        } else if (weather.contains("阴")) {
            if (type == 0) {
                res = weatherBgs[1];
            } else {
                res = weatherIcons[1];
            }
        } else if (weather.contains("多云")) {
            if (type == 0) {
                res = weatherBgs[2];
            } else {
                res = weatherIcons[2];
            }
        } else if (weather.contains("雾霾")) {
            if (type == 0) {
                res = weatherBgs[4];
            } else {
                res = weatherIcons[4];
            }
        } else if (weather.contains("雾")) {
            if (type == 0) {
                res = weatherBgs[3];
            } else {
                res = weatherIcons[3];
            }
        } else if (weather.contains("沙尘暴")) {
            if (type == 0) {
                res = weatherBgs[5];
            } else {
                res = weatherIcons[5];
            }
        } else if (weather.contains("冰雹")) {
            if (type == 0) {
                res = weatherBgs[6];
            } else {
                res = weatherIcons[6];
            }
        } else if (weather.contains("雷电") || weather.contains("雷阵雨") || weather.contains("闪电")) {
            if (type == 0) {
                res = weatherBgs[7];
            } else {
                res = weatherIcons[7];
            }
        } else if (weather.contains("雪")) {
            if (type == 0) {
                res = weatherBgs[8];
            } else {
                res = weatherIcons[8];
            }
        } else if (weather.contains("小雨")) {
            if (type == 0) {
                res = weatherBgs[9];
            } else {
                res = weatherIcons[9];
            }
        } else if (weather.contains("大雨") || weather.contains("暴雨") || weather.contains("大到暴雨")) {
            if (type == 0) {
                res = weatherBgs[10];
            } else {
                res = weatherIcons[10];
            }
        } else if (weather.contains("中雨")) {
            if (type == 0) {
                res = weatherBgs[11];
            } else {
                res = weatherIcons[11];
            }
        } else if (weather.contains("阵雨")) {
            if (type == 0) {
                res = weatherBgs[12];
            } else {
                res = weatherIcons[12];
            }
        } else if (weather.contains("霜冻")) {
            if (type == 0) {
                res = weatherBgs[13];
            } else {
                res = weatherIcons[13];
            }
        } else {
            if (type == 0) {
                res = weatherBgs[0];
            } else {
                res = weatherIcons[0];
            }
        }
        return res;
    }

    private void registerBroad() {
        try {
            if (receiveBroadcast == null) {
                receiveBroadcast = new ReceiveBroadcast();
                IntentFilter filter = new IntentFilter();
                filter.addAction(BaseConstant.ACTION_LOCATION_LOC);
                getActivity().registerReceiver(receiveBroadcast, filter);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class ReceiveBroadcast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (intent.getAction().equals(BaseConstant.ACTION_LOCATION_LOC)) {
                    BDLocation bdLocation = intent.getParcelableExtra(BaseConstant.INTENT_CONTENT);
                    if (bdLocation == null) {
                        if (StringUtil.isEmpty(SharedUtil.getChooseCity(context))) {
                            homeCity.setText(getString(R.string.location2));
                        }
                    } else {
                        if (StringUtil.isEmpty(SharedUtil.getCity(context))) {
                            if (StringUtil.isEmpty(SharedUtil.getChooseCity(context))) {
                                homeCity.setText(getString(R.string.location2));
                            }
                        } else {
                            if (StringUtil.isEmpty(SharedUtil.getChooseCity(context))) {
                                SharedUtil.saveChooseCity(context, SharedUtil.getCity(context), SharedUtil.getCityCode(context));
                                homeCity.setText(SharedUtil.getChooseCity(context));
                                getWeather();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}